package com.mproject.activity;

import com.mproject.activity.project.Project_Message_Detail;
import com.mproject.activity.project.Project_TabView;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class C2DMMessageReceiver extends BroadcastReceiver {

	public static final String BROADCAST_ACTION = "com.mproject.activity.displayevent";
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.w("C2DM", "Message Receiver called");
		if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
			Log.w("C2DM", "Received message");
			final String payload = intent.getStringExtra("payload");
			Log.d("C2DM", "dmControl: payload = " + payload);
			// TODO Send this to my application server to get the real data
			// Lets make something visible to show that we received the message
			createNotification(context, payload);

		}
	}

	public void createNotification(Context context, String payload) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_launcher,
				"Message received", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		if(Project_Message_Detail.isCurrent==true)
		{
			//TabView.flag=1;
			/*intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);*/
			Intent msgIntent = new Intent(BROADCAST_ACTION);
			context.sendBroadcast(msgIntent);

		}
		else {

			Intent intent = new Intent(context, LoginActivity.class);
			intent.putExtra("payload", payload);
			PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
					intent, 0);
			notification.setLatestEventInfo(context, "Message",
					payload, pendingIntent);
			notificationManager.notify(0, notification);
		}

	}

}

